package com.cls.business.service.impl;

import com.cls.business.entity.*;
import com.cls.business.service.IIndicatorDetailService;
import com.cls.business.service.IIndicatorService;
import com.cls.common.entity.QueryRequest;
import com.cls.business.mapper.StandardMapper;
import com.cls.business.service.IStandardService;
import com.cls.common.service.RedisService;
import com.cls.common.utils.StringUtils;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import lombok.RequiredArgsConstructor;
import com.github.pagehelper.PageHelper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.List;

/**
 * 评审标准表 Service实现
 *
 * @author wmm
 * @date 2020-11-11 16:25:41
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class StandardServiceImpl extends ServiceImpl<StandardMapper, Standard> implements IStandardService {

    @Autowired
    private IIndicatorService indicatorService;
    @Autowired
    private IIndicatorDetailService indicatorDetailService;

    @Override
    public PageInfo<Standard> findStandards(QueryRequest request, Standard standard) {
        LambdaQueryWrapper<Standard> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        if(!StringUtil.isEmpty(standard.getName())) {
            //单字段模糊查询
            queryWrapper.like(Standard::getName,standard.getName());
            //多字段模糊查询
            /*queryWrapper.and(wrapper ->
                    wrapper.like(Standard::getName, standard.getName()).or().like(Standard::getExplainContent, standard.getName()));*/
        }
        if(standard.getSnapshot()!=null) {
            //不为快照
            queryWrapper.eq(Standard::getSnapshot,standard.getSnapshot());
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Standard> list= this.list(queryWrapper);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public List<Standard> findStandards(Standard standard) {
	    LambdaQueryWrapper<Standard> queryWrapper = new LambdaQueryWrapper<>();
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }
    @Override
    public Standard getListStandards() {
        Standard standard=this.baseMapper.selectFindOne();
        Indicator indicator =new Indicator();
        indicator.setStandardId(standard.getStandardId());
        List<Indicator> indicators = indicatorService.findIndicators(indicator);
        for (Indicator item: indicators) {
            IndicatorDetail indicatorDetail=new IndicatorDetail();
            indicatorDetail.setIndicatorId(item.getIndicatorId());
            List<IndicatorDetail> indicatorDetails = indicatorDetailService.findIndicatorDetails(indicatorDetail);
            item.setIndicatorDetailLists(indicatorDetails);
        }
        standard.setIndicatorLists(indicators);
        return standard;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createStandard(Standard standard) {
        this.save(standard);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createStandardAll(StandardJson standardJson) {
        Standard standard =new Standard();
        standard.setName(standardJson.getName());
        standard.setExplainContent(standardJson.getExplainContent());
        standard.setSnapshot(false);
        this.save(standard);
        System.out.println(standard);
        List<StandardDateilDate> listSoure = standardJson.getListSoure();
        for (StandardDateilDate date:listSoure) {
            Indicator indicator=new Indicator();
            indicator.setStandardId(standard.getStandardId());
            indicator.setName(date.getName());
            indicator.setDescription(date.getDescription());
            indicator.setWeight(Double.valueOf(date.getWeight()));
            indicatorService.save(indicator);

            String[] indicatorTypeStrArr=date.getIndicatorTypeStrArr();
            String[] questionDescriptionStrArr=date.getQuestionDescriptionStrArr();
            String[] maxScoreStrArr=date.getMaxScoreStrArr();
            String[] minScoreStrArr=date.getMinScoreStrArr();
            for (int i=0;i<indicatorTypeStrArr.length; i++) {
                IndicatorDetail indicatorDetail=new IndicatorDetail();
                indicatorDetail.setIndicatorId(indicator.getIndicatorId());
                indicatorDetail.setIndicatorType(indicatorTypeStrArr[i]);
                indicatorDetail.setQuestionDescription(questionDescriptionStrArr[i]);
                indicatorDetail.setMaxScore(Double.valueOf(maxScoreStrArr[i]));
                indicatorDetail.setMinScore(Double.valueOf(minScoreStrArr[i]));
                indicatorDetailService.save(indicatorDetail);
            }
            System.out.println("新增完成");

        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStandard(Standard standard) {
        this.saveOrUpdate(standard);
    }


    /**
    * 删除
    * @param ids
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteStandards(String[] ids) {
        List< String > list = Arrays.asList(ids);
        this.removeByIds(list);
     }
    /**
     * 删除所有子信息
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeAllById(Long id) {
        this.removeById(id);
        Indicator indicator=new Indicator();
        indicator.setStandardId(id);
        List<Indicator> indicators = indicatorService.findIndicators(indicator);
        for (Indicator item:indicators) {
            indicatorService.removeById(item.getIndicatorId());
            IndicatorDetail indicatorDetail=new IndicatorDetail();
            indicatorDetail.setIndicatorId(item.getIndicatorId());
            List<IndicatorDetail> indicatorDetails = indicatorDetailService.findIndicatorDetails(indicatorDetail);
            indicatorDetails.forEach(e->{
                indicatorDetailService.removeById(e.getIndicatorDetailId());
            });
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long snapshotStandard(Standard standard) {
        LambdaQueryWrapper<Standard> queryWrapper = new LambdaQueryWrapper<>();
        if(standard.getSnapshot() != null){
            queryWrapper.eq(Standard::getSnapshot, standard.getSnapshot());
        }

        if(standard.getStandardId() != null){
            queryWrapper.eq(Standard::getStandardId, standard.getStandardId());
        }

        // 获取最新标准快照
        List<Standard> snapshots = baseMapper.selectList(queryWrapper);
        if(snapshots == null || snapshots.size() != 1){
            return -1L;
        }
        Standard snapshot = snapshots.get(0);
        // 获取最新标准下各项指标快照
        Indicator param = new Indicator();
        param.setStandardId(snapshot.getStandardId());
        List<Indicator> snapshotIndicators = indicatorService.findIndicators(param);

        // 插入标准快照，并生成新的标准ID
        snapshot.setSnapshot(true);
        save(snapshot);

        for(Indicator indicator:snapshotIndicators){
            // 获取最新标准下各项指标详情快照
            IndicatorDetail detailParam = new IndicatorDetail();
            detailParam.setIndicatorId(indicator.getIndicatorId());
            List<IndicatorDetail> snapshotDetails = indicatorDetailService.findIndicatorDetails(detailParam);

            // 将新的标准ID和即将插入的指标数据绑定，并插入指标数据
            indicator.setStandardId(snapshot.getStandardId());
            indicatorService.save(indicator);
            if(snapshotDetails != null && snapshotDetails.size() > 0){
                for(IndicatorDetail  detail: snapshotDetails){
                    detail.setIndicatorId(indicator.getIndicatorId());
                }
                snapshotDetails.forEach(item->{
                    indicatorDetailService.save(item);
                });
            }
        }
        return snapshot.getStandardId();
    }
}
